package com.yuanfeng.payment.service.impl;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.yuanfeng.commoms.config.ALiPayConfig;
import com.yuanfeng.commoms.config.YFConfig;
import com.yuanfeng.commoms.constant.CommonType;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.PayToolUtil;
import com.yuanfeng.commoms.util.RedisUtil;
import com.yuanfeng.commoms.util.ResponseResult;
import com.yuanfeng.commoms.util.StringUtils;
import com.yuanfeng.payment.feign.UsermsServiceClient;
import com.yuanfeng.payment.mapper.PayConfigMapper;
import com.yuanfeng.payment.mapper.PayConsumeRecordMapper;
import com.yuanfeng.payment.mapper.PayConsumeTradeBackMapper;
import com.yuanfeng.payment.service.PayStrategyHandleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * 支付宝PC支付
 *
 * @author Stranger
 * @date 2023/4/27 9:35
 */
@Service
public class AliPayPlusServiceImpl implements PayStrategyHandleService {


    private static PayConfigMapper payConfigMapper;


    private static PayConsumeTradeBackMapper payConsumeTradeBackMapper;


    private static PayConsumeRecordMapper payConsumeRecordMapper;


    private static UsermsServiceClient usermsServiceClient;


    // 注入的时候，给类的 service 注入
    @Autowired
    public void setMapper(PayConfigMapper payConfigMapper, PayConsumeTradeBackMapper payConsumeTradeBackMapper, PayConsumeRecordMapper payConsumeRecordMapper) {
        AliPayPlusServiceImpl.payConfigMapper = payConfigMapper;
        AliPayPlusServiceImpl.payConsumeRecordMapper = payConsumeRecordMapper;
        AliPayPlusServiceImpl.payConsumeTradeBackMapper = payConsumeTradeBackMapper;

    }

    // 注入的时候，给类的 service 注入
    @Autowired
    public void setUsermsServiceClient(UsermsServiceClient usermsServiceClient) {

        AliPayPlusServiceImpl.usermsServiceClient = usermsServiceClient;
    }

    /**
     * 初始化 阿里云支付参数
     */
    public void initAliPayConfig() {
        //从redis中查询
        String payStr = RedisUtil.get(YFConfig.ALI_PAY_CONFIG);
        Map<String, Object> aliPayConfig;
        if (StringUtils.isEmpty(payStr)) {
            aliPayConfig = payConfigMapper.selectPayConfig("03");
        } else {
            aliPayConfig = JSON.parseObject(payStr, Map.class);
            //将支付配置存入Redis
            RedisUtil.set(YFConfig.ALI_PAY_CONFIG, JSON.toJSON(aliPayConfig).toString());
        }
        if (null != aliPayConfig) {
            ALiPayConfig.URL = aliPayConfig.get("gatewayURL").toString();
            ALiPayConfig.APPID = aliPayConfig.get("appID").toString();
            ALiPayConfig.sellerId = aliPayConfig.get("appMCHId").toString();
            ALiPayConfig.RSA_PRIVATE_KEY = aliPayConfig.get("appAPIKey").toString();
            ALiPayConfig.CERT_PATH = aliPayConfig.get("cert_public_key_res2").toString();
            ALiPayConfig.ROOT_CERT_PATH = aliPayConfig.get("cert_root_key").toString();
            ALiPayConfig.ALIPAY_PUBLIC_CERT_PATH = aliPayConfig.get("cert_app_public_key").toString();
            ALiPayConfig.shopping_notify_url = aliPayConfig.get("shoppingNotifyUrl").toString();
            ALiPayConfig.shopping_notify_url_h5 = aliPayConfig.get("rechargeNotifyUrl2").toString();
            ALiPayConfig.shopping_return_url_pc = aliPayConfig.get("shoppingReturnUrlPc").toString();
            ALiPayConfig.PLUS_NOTIFY_URL = aliPayConfig.get("shoppingReturnUrlPc").toString();
        }

    }

    @Override
    public ResponseResult userPayEntrance(Map<Object, Object> para, HttpServletRequest request, HttpServletResponse response) {
        //创建支付单号
        int i = PayToolUtil.buildRandom(6);
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        StringBuffer plusorder = new StringBuffer("PLUS");
        plusorder.append(format.format(new Date()));
        plusorder.append(i);

        BigDecimal totalPrice = new BigDecimal(String.valueOf(para.get("payPrice")));

        String ordername = null;
        if (para.get("thaliType").equals(CommonType.plusThaliType.PLUS_THALI_MOON.getCode())){
            ordername = CommonType.plusThaliType.PLUS_THALI_MOON.getDesc();
        }else if(para.get("thaliType").equals(CommonType.plusThaliType.PLUS_THALI_SEASON.getCode())){
            ordername = CommonType.plusThaliType.PLUS_THALI_MOON.getDesc();
        }else{
            ordername = CommonType.plusThaliType.PLUS_THALI_YEAR.getDesc();
        }

        String price = String.valueOf(totalPrice);
        try {
            CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
            // 支付宝网关
            certAlipayRequest.setServerUrl(ALiPayConfig.URL);
            // 应用id
            certAlipayRequest.setAppId(ALiPayConfig.APPID);
            // 应用私钥路径
            certAlipayRequest.setPrivateKey(ALiPayConfig.RSA_PRIVATE_KEY);
            // 应用公钥路径
            certAlipayRequest.setCertPath(ALiPayConfig.ALIPAY_PUBLIC_CERT_PATH);
            // 支付宝应用公钥证书路径
            certAlipayRequest.setAlipayPublicCertPath(ALiPayConfig.CERT_PATH);
            // 支付宝证书，根证书路径
            certAlipayRequest.setRootCertPath(ALiPayConfig.ROOT_CERT_PATH);
            //设置签名
            certAlipayRequest.setSignType(ALiPayConfig.SIGNTYPE);
            // 设置签名类型
            certAlipayRequest.setFormat(ALiPayConfig.FORMAT);
            // 设置编码
            certAlipayRequest.setCharset(ALiPayConfig.CHARSET);

            AlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);

            // 设置请求参数
            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();

            // 商户订单号，商户网站订单系统中唯一订单号，必填
            String outTradeNo = plusorder.toString();
            // 付款金额，必填
            String totalAmount = price;
            // 订单名称，必填
            String subject = ordername;
            // 商品描述，可空
            String body = "购物";
            // 封装请求支付信息
            AlipayTradePagePayModel model = new AlipayTradePagePayModel();
            para.put("out_trade_no",outTradeNo);
            model.setPassbackParams(JSON.toJSONString(para));
            model.setOutTradeNo(outTradeNo);
            model.setTotalAmount(totalAmount);
            model.setSubject(subject);
            model.setBody(body);
            model.setTimeoutExpress("30m");
            // 销售产品码 必填
            model.setProductCode("FAST_INSTANT_TRADE_PAY");
            alipayRequest.setBizModel(model);
            alipayRequest.setReturnUrl(ALiPayConfig.shopping_return_url_pc);
            alipayRequest.setNotifyUrl(ALiPayConfig.PLUS_NOTIFY_URL);

            // 调用SDK生成表单
            String result = alipayClient.pageExecute(alipayRequest).getBody();
            response.setContentType("text/html;charset=" + ALiPayConfig.CHARSET);
            return ResponseResult.success(result);
        } catch (Exception e) {
        }
        return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL.getCode(), BizCodeEnume.TOKEN_IS_ILLEGAL.getMsg());
    }

}
